#!/bin/bash

if [[ $# -ne 1 ]]; then
    echo "The format is as follows:"
    echo "bash NAMD-2.13.sh  installpath"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1

installpath=$1
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}

set -e
yum install -y m4 environment-modules systemd-devel
wget -t 0 -c -P $installpath https://www.ks.uiuc.edu/Research/namd/2.13/download/412487/NAMD_2.13_Source.tar.gz
tar -zxvf $installpath/NAMD_2.13_Source.tar.gz -C $installpath && rm -rf $installpath/NAMD_2.13_Source.tar.gz
cd $installpath/NAMD_2.13_Source

charm=''$installpath'/CHARM'
cp arch/Linux-x86_64.fftw3 arch/Linux-ARM64.fftw3
sed -i '5d' Make.charm
sed -i '4a CHARMBASE = '$charm'' Make.charm
sed -i '1,12d' arch/Linux-ARM64-g++.arch
sed -i '1a NAMD_ARCH = Linux-ARM64\
CHARMARCH = mpi-linux-arm8\
FLOATOPTS = -O3 -ffast-math -funsafe-math-optimizations -fomit-frame-pointer -march=armv8-a\
CXX = g++ -std=c++11\
CXXOPTS = $(FLOATOPTS)\
CXXNOALIASOPTS = $(FLOATOPTS) -fno-strict-aliasing\
CC = gcc\
COPTS = $(FLOATOPTS)' arch/Linux-ARM64-g++.arch

sed -i 's|CXXFLAGS = $(CXXBASEFLAGS) $(CXXOPTS)|CXXFLAGS = $(CXXBASEFLAGS) $(CXXOPTS) -march=armv8.2-a -fsigned-char|g' Makefile
sed -i 's|CFLAGS = $(COPTI)$(SRCDIR) $(TCL) $(COPTS) $(RELEASE) $(EXTRADEFINES) $(TRACEOBJDEF)|CFLAGS = $(COPTI)$(SRCDIR) $(TCL) $(COPTS) $(RELEASE) $(EXTRADEFINES) $(TRACEOBJDEF) -march=armv8.2-a -fsigned-char|g' Makefile

FFTW=''$installpath'/FFTW'
TCL=''$installpath'/tcl8.5.9-linux-arm64-threaded'
./config Linux-ARM64-g++ --with-fftw3 --fftw-prefix $FFTW --with-tcl --tcl-prefix $TCL --charm-arch mpi-linux-arm8 --cxx clang++ --cc clang
cd Linux-ARM64-g++
make -j$(nproc)

cat>"$installpath/NAMD_2.13_Source/namd_modulefiles"<<EOF
#%Module1.0
conflict namd
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set NAMD \$pwd
setenv NAMD \$NAMD
prepend-path PATH \$NAMD/Linux-ARM64-g++
EOF

